﻿using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using AMM.CustomClassLibrary;
using AMM.DataModel;

namespace AMM.DataAccess {
    public class BaseRepository<TB> where TB : class, new() {
        protected AMM2014Entities Context {
            get {
                EntityConnectionStringBuilder csb = new EntityConnectionStringBuilder();
                csb.Metadata = "res://*/AMM2014.csdl|res://*/AMM2014.ssdl|res://*/AMM2014.msl";
                csb.Provider = "System.Data.SqlClient";
#if DEBUG
                csb.ProviderConnectionString = ConfigurationManager.AppSettings["AMMConnectionString"];
#else
                csb.ProviderConnectionString = SecurityHelper.DESDecrypt(ConfigurationManager.AppSettings["AMMConnectionString"]);
#endif
                return new AMM2014Entities(csb.ToString());
            }
        }

        public virtual void Insert(TB t) {
            using (var ctx = this.Context) {
                ctx.Set<TB>().Add(t);
                ctx.Entry<TB>(t).State = EntityState.Added;
                ctx.SaveChanges();
            }
        }

        public virtual void Update(TB t) {
            using (var ctx = this.Context) {
                ctx.Set<TB>().Add(t);
                ctx.Entry<TB>(t).State = EntityState.Modified;
                ctx.SaveChanges();
            }
        }

        public virtual void Delete(TB t) {
            using (var ctx = this.Context) {
                ctx.Set<TB>().Add(t);
                ctx.Entry<TB>(t).State = EntityState.Deleted;
                ctx.SaveChanges();
            }
        }

        public void DeleteMultiple(string sqlString) {
            using (var ctx = this.Context) {
                using (SqlConnection conn = (SqlConnection)ctx.Database.Connection) {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand()) {
                        cmd.Connection = conn;
                        cmd.CommandText = sqlString;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
    }
}
